/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* build(vector<int>& preorder,vector<int>& inorder,int& pos,int begin,int end)//注意pos一定要引用
    {
        if(begin>end) return nullptr;
        TreeNode* root=new TreeNode(preorder[pos]);
        int p=begin;
        while(p<=end)
        {
            if(inorder[p]==preorder[pos])
            {
                break;
            }
            else p++;
        }
        pos++;
        //此时p等于中序里面的根
        root->left=build(preorder,inorder,pos,begin,p-1);
        root->right=build(preorder,inorder,pos,p+1,end);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int pos=0;
        TreeNode* head=build(preorder,inorder,pos,0,inorder.size()-1);
        return head;
    }
};